import { _decorator, Tween, tween, UIOpacity, v3, view, Node } from 'cc';
import { LayerType } from '../../Config/BaseEnum';
import { PoolFactory } from '../../Component/PoolFactory';
import { ITipsObject, TipsObjectType } from '../../../Game/Config/GameEnum';
import { NodeRecycle } from '../../Manager/PoolManager';
const { ccclass, property } = _decorator;

@ccclass('FlyTipsPanel')
export class FlyTipsPanel extends NodeRecycle {
  panelLayer: LayerType;
  loadRes: string[];
  @property(PoolFactory)
  factory: PoolFactory = null!;

  private taskTipsNode: Node[] = [];
  private taskTipsIndex: number = 0;

  /** 弹出提示 */
  flyTips(data: ITipsObject) {
    const tips = this.factory.pop(data.data.node, data);
    this.pushTips(tips);
  }

  fly(data: ITipsObject) {
    switch (data.type) {
      case TipsObjectType.flyTips:
        this.factory.pop(data.data.node, data);
        break;
      case TipsObjectType.flyText:
        this.factory.pop(data.data.node, data);
        break;
      default:
        break;
    }
  }

  private pushTips(tips: Node) {
    if (this.taskTipsIndex >= this.taskTipsNode.length) {
      this.taskTipsNode.push(tips);
      this.moveUpTips();
    } else {
      this.taskTipsNode.push(tips);
    }
  }

  private shiftTips() {
    const temp = this.taskTipsNode.shift();
    this.taskTipsIndex--;
    if (temp) {
      const uiOpacity = temp.getComponent(UIOpacity);
      Tween.stopAllByTarget(temp);
      Tween.stopAllByTarget(uiOpacity);
      this.factory.push(temp);
    }
  }

  private tipsTween(tips: Node) {
    if (tips == null) return;
    const trans = view.getVisibleSize();
    this.node.addChild(tips);
    const uiOpacity = tips.getComponent(UIOpacity);
    Tween.stopAllByTarget(tips);
    Tween.stopAllByTarget(uiOpacity);
    uiOpacity.opacity = 255;
    tips.setPosition(trans.width / 2 + 262, 150);
    tween(tips)
      .to(0.2, { position: v3(trans.width / 2, 150) }, { easing: 'backOut' })
      .call(() => {
        this.taskTipsIndex++;
        this.moveUpTips();
      })
      .delay(1.3)
      .call((tag) => {
        const uiO = tag.getComponent(UIOpacity);
        tween(uiO).to(0.5, { opacity: 0 }).call(this.shiftTips.bind(this)).start();
      })
      .start();
  }

  private moveUpTips() {
    if (this.taskTipsIndex > 0 && this.taskTipsIndex < this.taskTipsNode.length) {
      // console.log("up tip:" + this.tempTipsIndex);
      let j = 0;
      const trans = view.getVisibleSize();
      while (j < this.taskTipsIndex) {
        tween(this.taskTipsNode[j])
          .to(0.2, { position: v3(trans.width / 2, (this.taskTipsIndex - j) * 99 + 150) })
          .start();
        j++;
      }
      setTimeout(() => {
        this.tipsTween(this.taskTipsNode[this.taskTipsIndex]);
      }, 200);
    } else {
      this.tipsTween(this.taskTipsNode[this.taskTipsIndex]);
    }
  }
}
